package com.warehouse.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;

public class JwtUtils {

    /**
     * 签名加密
     * */
    private static final String SING = "bbBjgjvbhBHBIujbBHBJKBNJKBgvfhcgvfYGVUHJVvjVVGjvh";


    /**
     * 生成token
     * */
    public static String getToken(String userName){
        Calendar instance = Calendar.getInstance();

        //设计过期时间为3天
        instance.add(Calendar.DATE,7);

        String token = JWT.create()
                .withClaim("username", userName)
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));


        return token;

    }

    /**
     * 验证token 合法性
     * 通过异常处理即可
     * */
    public static void verify(String token) {
         JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }


    /**

     * 获取token信息方法
     * */
    public static String analysisToken(String token) {

        DecodedJWT verify;
        verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
        Claim username = verify.getClaims().get("username");
        return username.asString();
    }

    public static void main(String[] args) {
        String token = getToken("123456");
        System.out.println(token);
    }

}
